<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>欢迎使用</title>
    <style>
        #bodyPart{
            margin: 0 auto;
            width: 500px;
            height: 700px;
        }
        #form{
            display: flex;
            border: 1px solid black;
            box-shadow: 5px 5px 5px black;
            padding: 10px;
            width: 400px;
            height: 500px;
            flex-direction: column;
            justify-content: space-around;
            margin: 0 auto;
        }
        h1{
            width: 400px;
            height: 50px;
            margin: 0 auto;
            font-family: '宋体';
            color: cadetblue;
        }
        .error {
            color: red;
            text-align: center;
        }
    </style>
</head>
<body>
    <div id="bodyPart">
        <h1>欢迎使用记账本 登录</h1>
        <form id="form">
            <label for="nickname">用户名：</label>
            <input type="text" id="nickname" name="nickname">
            <label for="userID">账户：</label>
            <input type="number" id="userID" name="userID">
            <label for="password">密码：</label>
            <input type="password" id="password" name="userPwd">
            <label for="email">邮箱：</label>
            <input type="email" id="email" name="userEmail">
            <button type="submit" id="sign">登录</button>
            <div id="errorMessage" class="error"></div>
        </form>
    </div>

    <script>
        document.getElementById('form').addEventListener('submit', async (e) => {
            e.preventDefault(); // ⚠️ 阻止默认表单跳转

            // 获取表单数据
            const formData = new FormData(e.target);
            const data = Object.fromEntries(formData.entries());

            // 发送登录请求
            try {
                const response = await fetch('/api/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                });

                const result = await response.json();

                if (result.code === '0000') {
                    // ✅ 登录成功：保存 token
                    localStorage.setItem('token', result.data);
                    alert('登录成功！');
                    // 跳转到事件列表页
                    window.location.href = '/eventlist.html';
                } else {
                    // ❌ 登录失败
                    document.getElementById('errorMessage').textContent = result.msg || '登录失败';
                }
            } catch (error) {
                console.error('登录请求失败:', error);
                document.getElementById('errorMessage').textContent = '网络错误，请重试';
            }
        });
    </script>
</body>
</html>